package com.yy.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yy.mapper.LockMapper;
import com.yy.pojo.Lock;

import java.util.concurrent.TimeUnit;

/**
 * @Author: chen
 * @Date: 2022/9/24 21:54
 * @Desc: 性能极低, 不推荐使用
 */
public class MysqlDistributeLock {
    LockMapper lockMapper;
    String lockName;

    public MysqlDistributeLock(LockMapper lockMapper, String lockName) {
        this.lockMapper = lockMapper;
        this.lockName = lockName;
    }

    public void lock() {
        while (!tryLock()) {
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private boolean tryLock() {
        try {
            Lock lock = new Lock();
            lock.setLockName(lockName);
            lockMapper.insert(lock);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public void unlock() {
        lockMapper.delete(new QueryWrapper<Lock>().eq("lock_name", lockName));
    }
}
